package sz.szsmk.citizencard.ui.dzsmkavtivity;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.IdRes;
import androidx.annotation.Nullable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.chenenyu.router.annotation.Route;
import com.gyf.immersionbar.ImmersionBar;

import java.util.List;

import javax.inject.Inject;

import sz.szsmk.citizencard.DaggerApplication;
import sz.szsmk.citizencard.R;
import sz.szsmk.citizencard.db.DaoSession;
import sz.szsmk.citizencard.db.SysConfDao;
import sz.szsmk.citizencard.model.network.bean.response.GetCodeResponse;
import sz.szsmk.citizencard.model.network.dzbean.res.BankCard;
import sz.szsmk.citizencard.model.network.dzbean.res.GetMyBankResponse;
import sz.szsmk.citizencard.model.network.dzbean.res.MessageEvent;
import sz.szsmk.citizencard.model.network.dzbean.res.PreAuthResult;
import sz.szsmk.citizencard.model.network.dzbean.res.SysConf;
import sz.szsmk.citizencard.mvp.BasePresenter;
import sz.szsmk.citizencard.mvp.MyBankCardMvpView;
import sz.szsmk.citizencard.mvp.RechargeMvpView;
import sz.szsmk.citizencard.mvp.dzsmkpresenter.MyBankCardPresenter;
import sz.szsmk.citizencard.mvp.dzsmkpresenter.RechargePresenter;
import sz.szsmk.citizencard.util.CashierInputFilter;
import sz.szsmk.citizencard.util.CommonUtils;
import sz.szsmk.citizencard.util.Constant;
import sz.szsmk.citizencard.util.PubUtils;
import sz.szsmk.citizencard.widget.GlobalVariables;
import sz.szsmk.citizencard.widget.PayPsdInputView;

/**
 * Created by yangzhengwen on 2017/10/1.
 */
@Route("RechargeActivity")
public class RechargeActivity extends AppBaseActivity implements RechargeMvpView, MyBankCardMvpView {

    ImageView reBankIcon;
    TextView ieBankName;
    TextView qrRechargeLimit;
    private PopupWindow popupWindow;
    private PopupWindow popResult;

    ImageView iv_qr_bank_icon;
    TextView tv_qr_bank_name;
    TextView tv_qr_bank_numl4;
    EditText et_qr_recharge;
    RadioGroup rg_qr_select;

    @Inject
    RechargePresenter rechargePresenter;
    @Inject
    MyBankCardPresenter mMyBankCardPresenter;

    private String money;

    private BankCard bankCard;

    private boolean isMain;

    private SysConf sysConf;
    private LinearLayout goChangeBank;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getComponent().inject(this);
        setContentView(R.layout.qr_activity_recharge);

        reBankIcon = findViewById(R.id.re_bank_icon);
        ieBankName = findViewById(R.id.ie_bank_name);
        qrRechargeLimit = findViewById(R.id.qr_recharge_limit);
        iv_qr_bank_icon = findViewById(R.id.iv_qr_bank_icon);
        tv_qr_bank_name = findViewById(R.id.tv_qr_bank_name);
        tv_qr_bank_numl4 = findViewById(R.id.tv_qr_bank_numl4);
        et_qr_recharge = findViewById(R.id.et_qr_recharge);
        rg_qr_select = findViewById(R.id.rg_qr_select);


        findViewById(R.id.tv_qr_recharge).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onClickView(v);
            }
        });


        ImmersionBar.with(this)
                .fitsSystemWindows(true)
                .statusBarDarkFont(true, 0f)
                .statusBarColor(R.color.white).init();
        goChangeBank = (LinearLayout) findViewById(R.id.go_change_bank);
        goChangeBank.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent intent = new Intent(RechargeActivity.this, BindBankCardActivity.class);
//                intent.putExtra("type", 1);
//                startActivity(intent);

                showPassword(v, "changebank");
            }
        });
//        DaoSession daoSession = DZSmkAppInit.getInstance().getDaoSession();
        DaoSession daoSession = DaggerApplication.getmDaoSession();
        SysConfDao sysConfDao = daoSession.getSysConfDao();
        List<SysConf> sysConfs = sysConfDao.loadAll();
        if (null != sysConfs && sysConfs.size() > 0) {
            sysConf = sysConfs.get(0);
            String limitMoney = sysConf.getRechargeFee()+"";
            long balance = CommonUtils.getLong(limitMoney);
            if (balance > 0) {
                String mLimitMoney = PubUtils.decimalFormatPrice(balance);
//                String format = String.format(getResources().getString(R.string.qr_no_enough_balance_limit), mBalanceLitmitMoney);
                qrRechargeLimit.setText("充值金额单笔不能低于" + mLimitMoney + "元");
            }
        }

        isMain = getIntent().getBooleanExtra("MainFragment", false);

        InputFilter[] is = {new CashierInputFilter()};
        et_qr_recharge.setFilters(is);
        rg_qr_select.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                RadioButton radioButton = (RadioButton) group.findViewById(checkedId);
                String result = radioButton.getText().toString();
                et_qr_recharge.setText(result.replace("元", ""));
            }
        });
    }

    @Override
    protected BasePresenter[] initPresenters() {
        return new BasePresenter[]{rechargePresenter, mMyBankCardPresenter};
    }


    public void onClickView(View v) {
        if (v.getId() == R.id.tv_qr_recharge) {
            money = et_qr_recharge.getText().toString();
            if (TextUtils.isEmpty(money)) {
                showTipDialog("请输入充值金额");
            } else if (sysConf != null && Integer.parseInt(money) * 100 < sysConf.getRechargeFee()) {
                showTipDialog("单次充值金额不能小于" + (sysConf.getRechargeFee() / 100) + "元");
            } else {
                showPassword(v, "recharge");
            }
        }
    }

    private void showPassword(View view, final String type) {
        View popView = getLayoutInflater().inflate(
                R.layout.qr_pop_password, null);
        final PayPsdInputView payPsdInputView = (PayPsdInputView) popView.findViewById(R.id.password);
        TextView tv_qr_cancel = (TextView) popView.findViewById(R.id.tv_qr_cancel);
        TextView tv_qr_ok = (TextView) popView.findViewById(R.id.tv_qr_ok);
        popupWindow = new PopupWindow(popView,
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);//popView即popupWindow的布局，ture设置focusAble.
        popupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
        popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        //必须设置BackgroundDrawable后setOutsideTouchable(true)才会有效。这里在XML中定义背景，所以这里设置为null;
//        popupWindow.setBackgroundDrawable(new BitmapDrawable(getResources(), (Bitmap) null));
//        popupWindow.setOutsideTouchable(true); //点击外部关闭。
        popupWindow.setAnimationStyle(android.R.style.Animation_Dialog);    //设置一个动画。
        backgroundAlpha(0.5f);
        //设置Gravity，让它显示在右上角。

        popupWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);


        tv_qr_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });

        tv_qr_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String password = payPsdInputView.getPasswordString();
                if (password.length() < 6) {
                    showTipDialog("密码位数不全");
                } else {
                    popupWindow.dismiss();
                    showLoadingDialog();
                    rechargePresenter.checkPayPassword(password, type);
                }
            }
        });

        popupWindow.setOnDismissListener(new poponDismissListener());
    }

    class poponDismissListener implements PopupWindow.OnDismissListener {

        @Override
        public void onDismiss() {
            //Log.v("List_noteTypeActivity:", "我是关闭事件");
            backgroundAlpha(1f);
        }
    }

    private void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().setAttributes(lp);
    }

    @Override
    protected CharSequence getTopTitle() {
        return getString(R.string.qr_recharge);
    }

    @Override
    public void onCheckSuccess(String type) {
        if (type.equals("recharge")) {
            showLoadingDialog();
            rechargePresenter.recharge(Integer.parseInt(money) * 100, bankCard.getBankCardId());
        } else {
            dismissLoadingDialog();
            Intent intent = new Intent(RechargeActivity.this, BindBankCardOldActivity.class);
            intent.putExtra("type", 1);
            startActivity(intent);
        }
    }

    @Override
    public void onCheckFailed(GetMyBankResponse getMyBankResponse) {
        dismissLoadingDialog();
        Toast.makeText(mContext, getMyBankResponse.getMessage(), Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mMyBankCardPresenter.gainMyBankCard();
    }

    @Override
    public void onRechargeSuccess() {
        dismissLoadingDialog();
//        showTipDialog("充值成功");
//        finish();
        PreAuthResult preAuthResult = GlobalVariables.getInstance(this).getPreAuthResult();
        preAuthResult.setUserStatus(Constant.QUERY_QR_RESULT_AUTHED);
        GlobalVariables.getInstance(this).setPreAuthResult(this, preAuthResult);
        showResult(true, "");
    }

    @Override
    public void onGainMyBankCard(List<BankCard> bankCards) {
        bankCard = bankCards.get(0);
        Glide.with(RechargeActivity.this).load(bankCard.getBankIconUrl()).placeholder(R.drawable.qr_ic_banklog).error(R.drawable.qr_ic_banklog).into(iv_qr_bank_icon);
        Glide.with(RechargeActivity.this).load(bankCard.getBankIconUrl()).placeholder(R.drawable.qr_ic_banklog).error(R.drawable.qr_ic_banklog).into(reBankIcon);
        tv_qr_bank_name.setText(bankCard.getBankName() + "");
        tv_qr_bank_numl4.setText(bankCard.getBankCardNumber() + "");
        ieBankName.setText(bankCard.getBankName() + "(" + bankCard.getBankCardNumber() + ")");


    }

    @Override
    public void onGainMyBankCardFail(GetMyBankResponse getMyBankResponse) {
        Toast.makeText(mContext, getMyBankResponse.getMessage(), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onRechargeFailed(GetCodeResponse getCodeResponse) {
        dismissLoadingDialog();
        showResult(false, getCodeResponse.getMessage());
    }

    private void showResult(final boolean success, String message) {
        View popView = getLayoutInflater().inflate(R.layout.qr_pop_recharge_result, null);
        TextView tv_qr_ok = (TextView) popView.findViewById(R.id.tv_qr_ok);
        ImageView iv_qr_recharge_status = (ImageView) popView.findViewById(R.id.iv_qr_recharge_status);
        TextView tv_qr_recharge_message = (TextView) popView.findViewById(R.id.tv_qr_recharge_message);
        TextView tv_qr_recharge_tip = (TextView) popView.findViewById(R.id.tv_qr_recharge_tip);
        if (success) {
            iv_qr_recharge_status.setImageResource(R.drawable.qr_recharge_success);
            tv_qr_recharge_message.setText("充值成功");
            tv_qr_recharge_tip.setVisibility(View.VISIBLE);
        } else {
            iv_qr_recharge_status.setImageResource(R.drawable.qr_recharge_failed);
            tv_qr_recharge_message.setText(message);
            tv_qr_recharge_tip.setVisibility(View.GONE);
        }
        popResult = new PopupWindow(popView,
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);//popView即popupWindow的布局，ture设置focusAble.

        //必须设置BackgroundDrawable后setOutsideTouchable(true)才会有效。这里在XML中定义背景，所以这里设置为null;
//        popupWindow.setBackgroundDrawable(new BitmapDrawable(getResources(), (Bitmap) null));
//        popupWindow.setOutsideTouchable(false); //点击外部关闭。
        popResult.setAnimationStyle(android.R.style.Animation_Dialog);    //设置一个动画。
        backgroundAlpha(0.5f);
        popResult.showAtLocation(findViewById(R.id.ll_qr_recharge), Gravity.CENTER, 0, 0);
        tv_qr_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popResult.dismiss();
                if (success) {
                    if (isMain) {
                        eventBus.post(new MessageEvent(MessageEvent.CODE_REFRESH));
                    } else {
                        eventBus.post(new MessageEvent(MessageEvent.CODE_UPDATE_BALANCE_SUCCESS));
                    }
                    finish();
                }

            }
        });
        popResult.setOnDismissListener(new poponDismissListener());
    }

    private void showTipDialog(String tip) {
        PubUtils.popTipOrWarn(RechargeActivity.this, tip);
    }
}
